package com.weixin.project.Aspect;

import com.weixin.project.Common.Enum.UserType;
import com.weixin.project.Entity.User;
import com.weixin.project.Util.ResponseUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class VipAccessAspect {
    @Pointcut("@annotation(com.weixin.project.Annotation.VipAccess)")
    public void vipAccess() {}

    @Around("vipAccess()")
    public Object checkVipAccess(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = getCurrentHttpRequest();
        User user = (User) request.getAttribute("current_user");
        //VIP能访问的接口ADMIN应该也能访问
        if (user != null && (user.getType().equals(UserType.VIP)
                || user.getType().equals(UserType.ADMIN))) {
            return joinPoint.proceed();
        } else {
//            throw new AccessDeniedException("Only VIP users are allowed to access this resource");
            return ResponseUtil.requireVIP();
        }
    }

    private HttpServletRequest getCurrentHttpRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? requestAttributes.getRequest() : null;
    }
}
